﻿using System.Data.Entity;
using System.Linq;
using IFDB.Models.Contexts;
using IFDB.Models.Tables;
using IFDB.ResourceLibrary;
using IFDB.ViewModels.PartialViewModels.Interfaces;
using PagedList;

namespace IFDB.ViewModels.PartialViewModels
{
    public class HeadToHeadViewModel : IHeadToHeadViewModel, IPaginationViewModel<Match>
    {
        #region Constructor
        public HeadToHeadViewModel(Match match, int page)
        {
            this.Match = match;
            this.page = page;
        }
        #endregion

        #region Fields
        private int page;
        private IPagedList<Match> headToHeadList;
        #endregion

        #region IHeadToHeadViewModel implementation
        public Match Match { get; set; }

        public IPagedList<Match> HeadToHeadList
        {
            get
            {
                if (headToHeadList == null)
                    using (IFDBContext db = new IFDBContext())
                        headToHeadList = (from m in db.Matches
                                              .Include(m => m.Team1)
                                              .Include(m => m.Team2)
                                          where (m.Team1Id == Match.Team1Id || m.Team1Id == Match.Team2Id) && (m.Team2Id == Match.Team1Id || m.Team2Id == Match.Team2Id)
                                          && (m.MatchStatus == MatchStatus.ScoreOnly || m.MatchStatus == MatchStatus.FullMatch)
                                          select m)
                                          .OrderByDescending(m => m.MatchDate)
                                          .ToPagedList(page, 10);

                return headToHeadList;
            }
        }
        #endregion

        #region IPaginationViewModel<Match> implementation
        public IPagedList<Match> PagedList
        {
            get { return HeadToHeadList; }
        }

        public string ActionName
        {
            get { return "_HeadToHeadList"; }
        }

        public string ControllerName
        {
            get { return "Match"; }
        }

        public object FirstHtmlAttributes
        {
            get { return new { matchId = Match.MatchId, page = 1 }; }
        }

        public object PreviousHtmlAttributes
        {
            get { return new { matchId = Match.MatchId, page = PagedList.PageNumber - 1 }; }
        }

        public object NextHtmlAttributes
        {
            get { return new { matchId = Match.MatchId, page = PagedList.PageNumber + 1 }; }
        }

        public object LastHtmlAttributes
        {
            get { return new { matchId = Match.MatchId, page = PagedList.PageCount }; }
        }

        public string TargetId
        {
            get { return "HeadToHeadMatchesTable"; }
        }
        #endregion
    }
}
